package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import dao.DishAuditDao;
import dao.MerchantAuditDao;
import po.DishAudit;
import po.MerchantAudit;
import vo.MerchantAuditVo;

@Repository("merchantAuditDao")
public class MerchantAuditDaoImpl implements MerchantAuditDao {
	
	@PersistenceContext(name="un")
	private EntityManager entityManager;
	
	@Autowired
	private DishAuditDao dad;

	@Transactional
	@Override
	public String insertMerchantAudit(MerchantAudit merchantAudit) {
		// TODO Auto-generated method stub
		entityManager.persist(merchantAudit);
		return merchantAudit.getmId();
	}

	@Override
	public List<MerchantAudit> listMerchantAudits() {
		// TODO Auto-generated method stub
		String jpql = "from MerchantAudit ma order by ma.status, ma.createDate desc";
		List<MerchantAudit> merchantAudits = entityManager.createQuery(jpql).getResultList();
		return merchantAudits;
	}

	@Override
	public MerchantAudit findMerchantAuditById(String id) {
		// TODO Auto-generated method stub
		MerchantAudit merchantAudit = null;
		merchantAudit = entityManager.find(MerchantAudit.class, id);			
		return merchantAudit;
	}

	@Transactional
	@Override
	public String updateMerchantAudit(MerchantAudit merchantAudit) {
		// TODO Auto-generated method stub
		entityManager.merge(merchantAudit);
		if(merchantAudit.getStatus() == 3){
			String jpql = "from DishAudit da where da.mId = :mId";
			List<DishAudit> list = entityManager.createQuery(jpql)
					.setParameter("mId", merchantAudit.getmId())
					.getResultList();
			if(list != null){				
				for (DishAudit dishAudit : list) {
					dishAudit.setStatus(2);
					dad.updateDishAudit(dishAudit);
				}
			}
		}
		return merchantAudit.getmId();
	}

	@Override
	public List<String> listBlackMerchant() {
		// TODO Auto-generated method stub
		String jpql = "select ma.mId from MerchantAudit ma where ma.status = 0 or ma.status = 2 or ma.status = 3";
		List<String> list = entityManager.createQuery(jpql).getResultList();
		return list;
	}

}
